<?php

namespace common\behavior\CommonMessagePushing;

use common\model\ProjectStepCategoryConfirmConfigModel;
use common\model\ReviewFeedbackConfirmModel;
use common\model\ReviewFeedbackModel;
use Webman\Stomp\Client;

/**
 * 需求单需要确认 消息通知
 */
class DemandOrderRequireConfirmBehavior
{
    /**
     * @param $params
     * @return void
     */
    public function run($params)
    {
        $demandOrder = model(ReviewFeedbackModel::class)->find($params['demand_order_id']);
        if (empty($demandOrder) || ($demandOrder['demand_type'] !== 'demand_order')) {
            return;
        }
        $demandOrder['step_category_ids'] = split_array($params['step_category_id'] ?? $demandOrder['step_category_ids']);
        $receiver = $params['receiver'] ?? [];
        if (empty($receiver)) {
            // 查询当前确认状态
            $userConfirmed = model(ReviewFeedbackConfirmModel::class)
                ->where(['review_feedback_id' => $demandOrder['id']])
                ->column('user_id');
            $where = [
                'project_id' => $demandOrder['project_id'],
                'step_category_id' => ['in', implode(',', $demandOrder['step_category_ids'])],
                'type' => 'demand_order_confirm',
            ];
            // 默认确认人 查询条件 - 默认仅通知未确认的
            if (!empty($userConfirmed) && !($params['notice_all'] ?? false)) {
                $where['confirm_user_id'] = [
                    'not in',
                    implode(',', $userConfirmed)
                ];
            }
            $defaultConfirmUser = model(ProjectStepCategoryConfirmConfigModel::class)
                ->where($where)
                ->column('confirm_user_id');
            // 区分确认人、再次确认人
            $receiver = array_map(fn($user) => [
                'user_id' => $user,
                'role' => in_array($user, $userConfirmed) ? 'reconfirm_user' : 'confirm_user'
            ], $defaultConfirmUser);
        }
        $data = [
            'source_user_id' => $demandOrder['created_by'],
            'time' => $demandOrder['created'],
            'end_time' => $params['end_time'] ?? 0,
            'source_id' => $demandOrder['id'],
            'source_module_code' => 'demand_order',
            'category' => 'demand_order_confirm',
            'receiver' => $receiver,
            'receiver_cc' => [],
        ];
        try {
            trace("common demand order confirm push behavior" . request()->getUnionUserId(), 'DEBUG');
            Client::send('common_message_pushing', build_queue_data_with_xu($data));
        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
        return;
    }
}
